<?php

namespace app\controller;

use app\model\application;
use app\model\items;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\Controller;

class Table extends Controller
{

    private $err;
    //用户guid
    private $userGuid;

    //模板 参考:default.json
    private $excelTpl;

    //模板文件名
    private $excelTplFileName;

    //电子表格实例
    private $spreadSheet;

    //电子表格头


    private $appModel;

    private $itemsModel;

    private $title;

    private $head;

    public function __construct()
    {
        parent::__construct();
        $this->appModel   = new application();
        $this->itemsModel = new items();

        $this->spreadSheet = new Spreadsheet();
        require __DIR__ . "/Common.php";
        $this->err = new \Err();
    }

    /**
     * 1 获取发布的填写项目
     */
    public function getItemsApi()
    {
        $items = $this->appModel->order("create_time desc")->select();
        return $this->err->info(0, $items);
    }

    //2 获取excel模板 ok
    public function getExcelTplApi($s = '')
    {
        return $this->err->info(0, $this->getExcelTpl($s));
    }

    //获取模板
    private function getExcelTpl($s = '')
    {
        return $this->appModel->find($s);
    }

    //3 添加填报项目
    public function addItemsApi()
    {
        $data                  = input('post.');
        $data['pk_items_guid'] = md5(time());
        return $this->err->infoUpd($this->itemsModel->save($data));
    }

    //4 具体表的条目
    public function itemsApi($s = '')
    {
        return $this->err->info(0, $this->getItems($s));
    }


    //5 获取具体的条目
    private function getItems($s = '')
    {
        return $this->itemsModel->where('fk_application_guid', $s)->select();
    }


    //6 添加填写项目
    public function createApply()
    {

    }



    /**
     * db转换为excel
     * @param string $q
     * @param bool $index 是否需要序号一栏
     */
    public function dbToExcel($q = '', $index = true)
    {
        $this->initExcel($q);
        $data  = $this->getItems($q);

        $az    = \Helper::getA2ToZ2();
        $i     = 0;
        $this->spreadSheet->getActiveSheet()->setCellValue("A1", $this->title);
        if ($index === true) {
            array_unshift($this->head, ['title' => '序号']);
        }
        foreach ($this->head as $key => $val) {
            $this->spreadSheet->getActiveSheet()->setCellValue($az[$i++], $val['title']);
        }
        $dataArray = [];
        $cellIndex = 0;
        foreach ($data as $key => $v) {
            $item = (json_decode($v->getData()['data'], true));

            if ($index === true) {

                array_unshift($item, ++$cellIndex);
            }
            $temp = [];

            foreach ($item as $v1) {
                array_push($temp, $v1);
            }
            array_push($dataArray, $temp);

        }
        $this->spreadSheet->getActiveSheet()->fromArray($dataArray, null, 'A3');
        // Redirect output to a client’s web browser (Ods)
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename=' . $this->title . ".xls");
        header('Cache-Control: max-age=0');

        $writer = IOFactory::createWriter($this->spreadSheet, 'Xls');
        $writer->save('php://output');
    }



    private function initExcel($q='')
    {
        $data=$this->appModel->find($q);
        $this->title=$data['title'];
        $this->head= (json_decode($data['tpl'], true))['head'];
    }

}
